package com.ygl.framework.jwt;

import com.ygl.entity.User;
import com.ygl.framework.exception.MyException;
import com.ygl.utils.Maps;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author ygl
 * @date 2021/7/8
 * @description JWT工具类
 */
public class JwtUtil {

    public static String token = "token";
    // 秘钥
    public static String SECRET = "ygl@cms@person@blog";
    // 过期时长
    public static long expr = 3600 * 24 * 1000;

    //1、生成token
    public static String sign(User user) {
        //1、指定签名使用的算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //2、生成签发时间
        long nowMillis = System.currentTimeMillis();
        Date date = new Date(nowMillis);
        //3、创建playLoad的私有申明
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("userName", user.getUserName());
        //4、生成签发人
        String subject = user.getUserName();
        JwtBuilder jwtBuilder = Jwts.builder()
                .setClaims(claims)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(date)
                .setSubject(subject)
                .signWith(signatureAlgorithm, SECRET);
        //设置过期时间
        jwtBuilder.setExpiration(new Date(nowMillis + expr));
        return jwtBuilder.compact();
    }

    //2、验证token
    public static boolean verify(String token) {
        try {
            if (StringUtils.isEmpty(token)) {
                return false;
            }
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    //3、获取用户信息
    public static User getUser(String token) {
        try {
            if (StringUtils.isEmpty(token)) {
                throw new MyException("token不能为空");
            }

            if (verify(token)) {
                Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
                User user = new User();
                user.setId(Integer.parseInt(claims.get("id") + ""));
                user.setUserName(claims.get("userName") + "");
                return user;
            } else {
                throw new MyException("超时或不合法token");
            }
        } catch (MyException e) {
            throw new MyException("超时或不合法token");
        }
    }

    public static void main(String[] args) {
        User user = new User();
        user.setId(1);
        user.setUserName("jwtygl");
        System.out.println(sign(user));
    }
}
